package com.csi.controller.user;

import com.alibaba.fastjson2.JSON;
import com.csi.pojo.Result;
import com.csi.service.UserService;
import com.csi.service.impl.UserServiceImpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@WebServlet("/user/uploadPathController")
public class UploadPathController extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型
        response.setContentType("application/json;charset=utf-8");

        // 创建文件上传对象
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        int userId = 0;
        String savePath = null;
        // 解析上传请求
        try {
            List<FileItem> items = upload.parseRequest(request);
            for (FileItem item : items) {
                // 判断是否是文件上传控件
                if (!item.isFormField()) {
                    // 获取上传文件的名称和内容
                    String fileName = item.getName();
                    InputStream inputStream = item.getInputStream();

                    // 生成新的文件名
                    String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                    String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;

                    // 要构建的文件夹路径
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM");
                    String path = "/uploads/" + sdf.format(date);

                    // 要保存的路径
                    savePath = path + "/" + newFileName;

                    // 保存上传文件到服务器
                    String uploadPath = getServletContext().getRealPath(path);
                    File uploadDir = new File(uploadPath);
                    if (!uploadDir.exists()) {
                        uploadDir.mkdirs();
                    }
                    File file = new File(uploadPath, newFileName);
                    OutputStream outputStream = new FileOutputStream(file);
                    byte[] buffer = new byte[1024];
                    int len;
                    while ((len = inputStream.read(buffer)) > 0) {
                        outputStream.write(buffer, 0, len);
                    }
                    outputStream.close();
                    inputStream.close();

                } else if ("userId".equals(item.getFieldName())) {
                    // 获取 userId 参数的值
                    String userIdStr = item.getString();
                    if (userIdStr != null && !userIdStr.isEmpty()) {
                        userId = Integer.parseInt(userIdStr);
                    }
                }
            }
            // 将文件信息保存到数据库中
            UserService userService = new UserServiceImpl();
            userService.uploadPath(savePath, userId);
            // 返回上传文件的路径
            Result<String> result = new Result<>();
            result.setCode(200);
            result.setMsg("文件上传成功");
            result.setDatas(savePath);
            PrintWriter out = response.getWriter();
            out.print(JSON.toJSONString(result));
            out.flush();
            out.close();
        } catch (FileUploadException e) {
            // 处理文件上传异常
            e.printStackTrace();
            Result<String> result = new Result<>();
            result.setCode(500);
            result.setMsg("文件上传失败");
            result.setDatas(null);
            PrintWriter out = response.getWriter();
            out.print(JSON.toJSONString(result));
            out.flush();
            out.close();
        }
    }
}
